#include "group.hpp"
#include "user.hpp"
#include "public.hpp"

#include "json.hpp"
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <chrono>
#include <ctime>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <semaphore.h>  // linux 的，C11 mutex+条件变量
#include <atomic>

using namespace std;
using json = nlohmann::json;

// 记录当前系统登录的用户信息
User g_currentUser;
// 记录当前登录用户的好友列表
vector<User> g_currentUserFriendList;
// 记录当前登录用户的群组列表信息
vector<Group> g_currentUserGroupList;
// 控制主菜单页面程序
bool isMainMenuRunning = false;
// 用于读写线程之间的通信
sem_t rwsem;
// 记录登录状态是否成功
atomic_bool g_isLoginSuccess(false);

// 接收线程
void readTaskHandler(int clientfd);
// 获取系统时间（聊天信息需要添加时间信息）
string getCurrentTime();
// 主聊天页面程序
void mainMenu(int clientfd);
// 显示当前登录成功用户的基本信息
void showCurrentUserData();

// 聊天客户端程序实现，main线程用作发送线程，子线程用作接收线程
int main(int argc, char **argv)
{
    if (argc < 3)
    {
        cerr << "command invalid! example: /ChatClent 127.0.0.1 6000" << endl;
        exit(-1);
    }

    // 解析通过 cmd 参数传递的IP和port
    char *ip = argv[1];
    uint16_t port = atoi(argv[2]);

    // 创建 client 端的 socket
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (clientfd == -1)
    {
        cerr << "socket create error" << endl;
    }

    // 填写 client 需要连接的 server 信息 ip+port
    sockaddr_in server;
    memset(&server, 0, sizeof(sockaddr_in));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip);

    // client 和 server 进行连接
    if (connect(clientfd, (sockaddr *)&server, sizeof(sockaddr_in)) == -1)
    {
        cerr << "connect server error" << endl;
        close(clientfd);
        exit(-1);
    }

    // 初始化主线程子线程通信的信号量
    sem_init(&rwsem, 0, 0);

    // connect 成功，启动子线程接收线程负责接收数据，该线程只启动一次
    std::thread readTask(readTaskHandler, clientfd);  // linux 底层调用 pthread_create
    readTask.detach();

    // main 线程用于接收用户输入，负责发送数据
    for (;;)
    {
        // 菜单
        cout << "=========================" << endl;
        cout << "1. login" << endl;
        cout << "2. register" << endl;
        cout << "3. quit" << endl;
        cout << "=========================" << endl;
        cout << "choice: ";
        int choice = 0;
        cin >> choice;
        cin.get();  // 读掉缓冲区残留的回车

        switch (choice)
        {
        case 1:  // login
        {
            int id = 0;
            char pwd[50] = {0};
            cout << "userid: ";
            cin >> id;
            cin.get();
            cout << "userpassword: ";
            cin.getline(pwd, 50);
            
            json js;
            js["msgid"] = LOGIN_MSG;
            js["id"] = id;
            js["password"] = pwd;
            string request = js.dump();

            g_isLoginSuccess = false;

            int len = send(clientfd, request.c_str(), strlen(request.c_str()) + 1, 0);
            if (len == -1)
            {
                cerr << "send login msg error: " << request << endl;
            }

            sem_wait(&rwsem);  // 等待由子线程处理完登录消息，通知这里
            if(g_isLoginSuccess == true)
            {
                // 进入聊天主菜单页面
                isMainMenuRunning = true;
                mainMenu(clientfd);
            }
        }
            break;

        case 2:  // register
        {
            char name[50] = {0};
            char pwd[50] = {0};
            cout << "username: ";
            cin.getline(name, 50);
            cout << "userpassword: ";
            cin.getline(pwd, 50);

            json js;
            js["msgid"] = REG_MSG;
            js["name"] = name;
            js["password"] = pwd;
            string request = js.dump();

            int len = send(clientfd, request.c_str(), strlen(request.c_str()) + 1, 0);
            if(len == -1)
            {
                cerr << "send reg msg error: " << request << endl;
            }

            sem_wait(&rwsem);
        }
            break;

        case 3:  // quit
            close(clientfd);
            sem_destroy(&rwsem);
            exit(0);
            break;
        default:
            cerr << "invalid input!" << endl;
            break;
        }
    }

    return 0;
}

// 显示当前登录成功用户的基本信息
void showCurrentUserData()
{
    cout << "=========================login user=========================" << endl;
    cout << "current login user => id:" << g_currentUser.getId() << " name:" << g_currentUser.getName() << endl;
    cout << "-------------------------friend list-------------------------" << endl;
    if (!g_currentUserFriendList.empty()) // 打印好友列表
    {
        for (User &user : g_currentUserFriendList)
        {
            cout << user.getId() << " " << user.getName() << " " << user.getState() << endl;
        }
    }
    cout << "-------------------------group list-------------------------" << endl;
    if (!g_currentUserGroupList.empty()) // 打印所在群组信息及所有群友
    {
        for (Group &group : g_currentUserGroupList)
        {
            cout << group.getId() << " " << group.getName() << " " << group.getDesc() << endl;
            for (GroupUser &groupUser : group.getUsers())
            {
                cout << groupUser.getId() << " " << groupUser.getName() << " " << groupUser.getState() << " " << groupUser.getRole() << endl;
            }
            cout << "------------------------------" << endl;
        }
    }
    cout << "============================================================" << endl << endl;
}

// 处理登录响应
void doLoginResponse(json &responsejs)
{
    if (responsejs["errno"].get<int>() != 0)  // 登录失败
    {
        cerr << responsejs["errmsg"] << endl;
        g_isLoginSuccess = false;
    }
    else  // 登陆成功
    {
        // 记录当前用户的 id 和 name
        g_currentUser.setId(responsejs["id"].get<int>());
        g_currentUser.setName(responsejs["name"]);

        // 记录当前用户的好友列表信息
        g_currentUserFriendList.clear();
        if (responsejs.contains("friends"))
        {
            vector<string> vec = responsejs["friends"];
            for (string &friendstr : vec)
            {
                json js = json::parse(friendstr);
                User friendUser;
                friendUser.setId(js["id"].get<int>());
                friendUser.setName(js["name"]);
                friendUser.setState(js["state"]);
                g_currentUserFriendList.push_back(friendUser);
            }
        }

        // 记录当前用户的群组列表信息
        g_currentUserGroupList.clear();
        if (responsejs.contains("groups"))
        {
            vector<string> groupVec = responsejs["groups"];
            for (string &groupstr : groupVec)
            {
                json groupJs = json::parse(groupstr);
                Group group;
                group.setId(groupJs["id"].get<int>());
                group.setName(groupJs["groupname"]);
                group.setDesc(groupJs["groupdesc"]);

                vector<string> groupUserVec = groupJs["users"];  // 群成员列表（群友）
                for (string &groupUserStr : groupUserVec)
                {
                    GroupUser groupFriend;
                    json js = json::parse(groupUserStr);
                    groupFriend.setId(js["id"].get<int>());
                    groupFriend.setName(js["name"]);
                    groupFriend.setState(js["state"]);
                    groupFriend.setRole(js["role"]);
                    group.setGroupUser(groupFriend);
                }

                g_currentUserGroupList.push_back(group);
            }
        }

        // 显示登录用户的基本信息
        showCurrentUserData();

        // 显示当前用户的离线消息 个人聊天信息或者群组消息
        if (responsejs.contains("offlinemsg"))
        {
            vector<string> vec = responsejs["offlinemsg"];
            for (string &str : vec)
            {
                json js = json::parse(str);
                // time [id] name said xxx
                if (js["msgid"].get<int>() == ONE_CHAT_MSG)
                {
                    cout << js["time"].get<string>() << " [" << js["id"] << "] " << js["name"].get<string>() << " said: " << js["msg"].get<string>() << endl;
                }
                else
                {
                    cout << "群消息 [" << js["groupid"] << "]: " << js["time"].get<string>() << " [" << js["id"] << "] " << js["name"].get<string>() << " said: " << js["msg"].get<string>() << endl;
                }
            }
            cout << endl;
        }

        g_isLoginSuccess = true;
    }
}

// 处理注册响应
void doRegisterResponse(json &responsejs)
{
    if (responsejs["errno"].get<int>() != 0)  // 注册失败
    {
        cerr << "name is already exist, register error" << endl;
    }
    else  // 注册成功
    {
        cerr << "name register success, user id is " << responsejs["id"] << ", don't forget it!" << endl;
    }
}

// 接收线程
void readTaskHandler(int clientfd)
{
    for(;;)
    {
        char buffer[1024] = {0};  // 用于接收数据
        int len = recv(clientfd, buffer, 1024, 0);
        if(len == -1 || len == 0)
        {
            close(clientfd);
            exit(-1);
        }

        // 接收ChatServer转发的数据
        json js = json::parse(buffer);
        int msgType = js["msgid"].get<int>();
        if(msgType == ONE_CHAT_MSG)
        {
            cout << js["time"].get<string>() << " [" << js["id"] << "] " << js["name"].get<string>() << " said: " << js["msg"].get<string>() << endl;
            continue;
        }
        
        if(msgType == GROUP_CHAT_MSG)
        {
            cout << "群消息 [" << js["groupid"] <<"]: " << js["time"].get<string>() << " [" << js["id"] << "] " << js["name"].get<string>() << " said: " << js["msg"].get<string>() << endl;
            continue;
        }

        // 登录响应消息
        if(msgType == LOGIN_MSG_ACK)
        {
            doLoginResponse(js);  // 处理登录响应的业务逻辑
            sem_post(&rwsem);   // 通知主线程登录结果处理完成
            continue;
        }

        // 注册响应消息
        if(msgType == REG_MSG_ACK)
        {
            doRegisterResponse(js);
            sem_post(&rwsem);   // 通知主线注册结果处理完成
            continue;
        }
    }
}

// 获取系统时间（聊天信息需要添加时间信息）
string getCurrentTime()
{
    auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    struct tm *ptm = localtime(&tt);
    char date[60] = {0};
    sprintf(date, "%04d-%02d-%02d %02d:%02d:%02d", (int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday, (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
    return std::string(date);
}

// "help" command handler
void help(int fd=0, string str = "");
// "chat" command handler
void chat(int, string);
// "addfriend" command handler
void addfriend(int, string);
// "creategroup" command handler
void creategroup(int, string);
// "addgroup" command handler
void addgroup(int, string);
// "groupchat" command handler
void groupchat(int, string);
// "logout" command handler
void logout(int, string);

// 系统支持的客户端命令列表
unordered_map<string, string> commandMap = {
    {"help", "显示所有支持的命令，格式 help"},
    {"chat", "一对一聊天，格式 chat:friendid:message"},
    {"addfriend", "添加好友，格式 addfriend:friendid"},
    {"creategroup", "创建群组，格式 creategroup:groupname:groupdesc"},
    {"addgroup", "加入群组，格式 addgroup:groupid"},
    {"groupchat", "群聊，格式 groupchat:groupid:message"},
    {"logout", "注销，格式 logout"}
};

// 注册系统支持的客户端命令处理  client msg
unordered_map<string, function<void(int, string)>> commandHandlerMap = {
    {"help", help},
    {"chat", chat},
    {"addfriend", addfriend},
    {"creategroup", creategroup},
    {"addgroup", addgroup},
    {"groupchat", groupchat},
    {"logout", logout}
};

// 主聊天页面程序
void mainMenu(int clientfd)
{
    help();

    char buffer[1024] = {0};
    while(isMainMenuRunning)
    {
        cin.getline(buffer, 1024);
        string commandBuf(buffer);
        string command;  // 存储命令

        int idx = commandBuf.find(":");
        if(idx == -1)
        {
            command = commandBuf;
        }
        else
        {
            command = commandBuf.substr(0, idx);
        }

        auto it = commandHandlerMap.find(command);
        if(it == commandHandlerMap.end())
        {
            cerr << "invalid input command!" << endl;
            continue;
        }

        // 调用相应命令的事件处理回调，mainMenu对修改封闭，添加新功能不需要修改该函数
        it->second(clientfd, commandBuf.substr(idx + 1, commandBuf.size() - idx));  // 调用命令处理方法
    }

    system("clear");
}

// "help" command handler
void help(int clientfd, string str)
{
    cout << "show command list:" << endl;
    for(auto &p : commandMap)
    {
        cout << p.first << " : " << p.second << endl;
    }
    cout << endl;
}

// "chat" command handler -- chat:friendid:message
void chat(int clientfd, string str)
{
    int idx = str.find(":");  // 这里找的是第二个冒号，因为传进来的 str 是后半部分子串
    if(idx == -1)
    {
        cerr << "chat command invalid!" << endl;
        return ;
    }

    int friendid = atoi(str.substr(0, idx).c_str());
    string message = str.substr(idx + 1, str.size() - idx);

    json js;
    js["msgid"] = ONE_CHAT_MSG;
    js["id"] = g_currentUser.getId();
    js["name"] = g_currentUser.getName();
    js["to"] = friendid;
    js["msg"] = message;
    js["time"] = getCurrentTime();
    string buffer = js.dump();

    int len = send(clientfd, buffer.c_str(), strlen(buffer.c_str()) + 1, 0);
    if(len == -1)
    {
        cerr << "send chat msg error -> " << buffer << endl;
    }
}

// "addfriend" command handler -- addfriend:friendid
void addfriend(int clientfd, string str)
{
    int friendid = atoi(str.c_str());

    json js;
    js["msgid"] = ADD_FRIEND_MSG;
    js["id"] = g_currentUser.getId();
    js["friendid"] = friendid;
    string buffer = js.dump();

    int len = send(clientfd, buffer.c_str(), strlen(buffer.c_str()) + 1, 0);
    if(len == -1)
    {
        cerr << "send addfriend msg error -> " << buffer << endl;
    }
}

// "creategroup" command handler -- creategroup:groupname:groupdesc
void creategroup(int clientfd, string str)
{
    int idx = str.find(":");
    if(idx == -1)
    {
        cerr << "create group command invalid!" << endl;
        return ;
    }

    string groupname = str.substr(0, idx).c_str();
    string groupdesc = str.substr(idx + 1, str.size() - idx);

    json js;
    js["msgid"] = CREATE_GROUP_MSG;
    js["id"] = g_currentUser.getId();
    js["groupname"] = groupname;
    js["groupdesc"] = groupdesc;
    string buffer = js.dump();

    int len = send(clientfd, buffer.c_str(), strlen(buffer.c_str()) + 1, 0);
    if(len == -1)
    {
        cerr << "send creategroup msg error -> " << buffer << endl;
    }
}

// "addgroup" command handler -- addgroup:groupid
void addgroup(int clientfd, string str)
{
    int groupid = atoi(str.c_str());

    json js;
    js["msgid"] = ADD_GROUP_MSG;
    js["id"] = g_currentUser.getId();
    js["groupid"] = groupid;
    string buffer = js.dump();

    int len = send(clientfd, buffer.c_str(), strlen(buffer.c_str()) + 1, 0);
    if(len == -1)
    {
        cerr << "send addgroup msg error -> " << buffer << endl;
    }
}

// "groupchat" command handler -- groupchat:groupid:message
void groupchat(int clientfd, string str)
{
    int idx = str.find(":");
    if(idx == -1)
    {
        cerr << "groupchat command invalid!" << endl;
        return ;
    }

    int groupid = atoi(str.substr(0, idx).c_str());
    string message = str.substr(idx + 1, str.size() - idx);

    json js;
    js["msgid"] = GROUP_CHAT_MSG;
    js["id"] = g_currentUser.getId();
    js["name"] = g_currentUser.getName();
    js["groupid"] = groupid;
    js["msg"] = message;
    js["time"] = getCurrentTime();
    string buffer = js.dump();

    int len = send(clientfd, buffer.c_str(), strlen(buffer.c_str()) + 1, 0);
    if(len == -1)
    {
        cerr << "send groupchat msg error -> " << buffer << endl;
    }
}

// "logout" command handler -- logout
void logout(int clientfd, string str)
{
    json js;
    js["msgid"] = LOGOUT_MSG;
    js["id"] = g_currentUser.getId();
    string buffer = js.dump();

    int len = send(clientfd, buffer.c_str(), strlen(buffer.c_str()) + 1, 0);
    if(len == -1)
    {
        cerr << "send logout msg error -> " << buffer << endl;
    }
    else
    {
        isMainMenuRunning = false;
    }
}